package com.carlinfo.servlet;

import com.alibaba.fastjson.JSON;
import com.carlinfo.servlet.domain.User;
import com.carlinfo.servlet.util.DataSourceUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Collections;
import java.util.List;

@WebServlet("/userServlet")
public class UserServlet extends HttpServlet
{
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
    {
        resp.setContentType("application/json;charset=utf8");
        QueryRunner queryRunner = new QueryRunner(DataSourceUtil.getInstance());
        String keyWord = req.getParameter("key");
        String sql = "select * from user where name like ?";
        try
        {
            if (keyWord != "")
            {
                List<User> query = queryRunner.query(sql, new BeanListHandler<User>(User.class), "%" + keyWord + "%");
                String jsonString = JSON.toJSONString(query);
                resp.getWriter().print(jsonString);

            } else
            {
                resp.getWriter().print(Collections.EMPTY_LIST);
            }
        } catch (SQLException e)
        {
            e.printStackTrace();
        }
    }
}
